package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.RiskDimension
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class VehicleController
{

    def springSecurityService
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def estateStatus = params["estateStatus"]
        def name = params["name"]
        def brand = params["brand"]
        def engineNumber = params["engineNumber"]
        def risk = params["risk"]
        def mortgageStatus = params["mortgageStatus"]
        def type = params["type"]
        def cashability = params["cashability"]

        def estateQueryParam = new HashMap()
        def user = User.findById(springSecurityService.principal.id)
        def estateSql = "from Collateral e where e.status = 'Completed' and e.type.code = 'vehicle' and e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city"
            estateQueryParam['city'] = city
        }
        if (estateStatus && estateStatus != "")
        {
            sql += " and e.estateStatus.id = :estateStatus"
            estateQueryParam['estateStatus'] = Long.parseLong(estateStatus)
        }
        if (name && name != "")
        {
            sql += " and e.name like :name "
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (brand && brand != "")
        {
            sql += " and e.vehicle.brand like :brand "
            estateQueryParam['brand'] = '%' + brand + '%'
        }
        if (engineNumber && engineNumber != "")
        {
            sql += " and e.vehicle.engineNumber like :engineNumber "
            estateQueryParam['engineNumber'] = '%' + engineNumber + '%'
        }
        if (risk && risk != "")
        {
            def riskList = RiskDimension.list()
            riskList.each {
                if (it?.label == risk)
                {
                    def minValue = it.minValue / 100
                    def maxValue = it.maxValue / 100
                    sql += " and e.cltv > :minValue and e.cltv <= :maxValue "
                    estateQueryParam['minValue'] = minValue
                    estateQueryParam['maxValue'] = maxValue
                }
            }
        }
        if (mortgageStatus && mortgageStatus != "")
        {
            sql += " and e.vehicle.mortgageStatus.id = :mortgageStatus "
            estateQueryParam['mortgageStatus'] = Long.parseLong(mortgageStatus)
        }
        if (type && type != "")
        {
            sql += " and e.vehicle.type.id = :type "
            estateQueryParam['type'] = Long.parseLong(type)
        }
        if (cashability && cashability != "")
        {
            sql += " and e.cashability.id = :cashability "
            estateQueryParam['cashability'] = Long.parseLong(cashability)
        }

        def countSql = " select count(e.id) from Collateral e where e.status = 'Completed' and e.type.code = 'vehicle' and e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql
        sql += " order by e.modifiedDate desc "
        estateSql += sql

        def collateralList = Collateral.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def collateralCount = Collateral.executeQuery(countSql, estateQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond collateralList, model: [collateralList: collateralList, collateralCount: collateralCount[0], districtList: districtList, params: params], view: 'index'
    }

    /**
     * 车辆类押品详情*/
    def show(Collateral collateral)
    {
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage
        respond collateral, model: [params: params, mortgageList: mortgageList, vehicleDetail: collateral?.vehicle]
    }

    def create()
    {
        respond new Vehicle(params)
    }

    @Transactional
    def save(Vehicle vehicle)
    {
        if (vehicle == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (vehicle.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond vehicle.errors, view: 'create'
            return
        }

        vehicle.save flush: true

        def collateral = new Collateral()
        collateral.province = vehicle.province
        collateral.city = vehicle.city
        collateral.district = vehicle.district
        collateral.estateStatus = vehicle.estateStatus
        collateral.isEstate = vehicle.isEstate
        collateral.unitPrice = vehicle.unitPrice
        collateral.totalPrice = vehicle.totalPrice
        collateral.valuationDate = vehicle.valuationDate
        collateral.ltv = vehicle.ltv
        collateral.cltv = vehicle.cltv
        collateral.account = vehicle.account
        collateral.externalId = vehicle.externalId
        collateral.name = vehicle.name
        collateral.fullName = vehicle.fullName
        collateral.identityType = vehicle.identityType
        collateral.idNumber = vehicle.idNumber
        collateral.loanCardNumber = vehicle.loanCardNumber
        collateral.commonOwnerFullName = vehicle.commonOwnerFullName
        collateral.sharePoint = vehicle.sharePoint
        collateral.cashability = vehicle.cashability
        collateral.valueVolatility = vehicle.valueVolatility
        collateral.seizureOfConvenience = vehicle.seizureOfConvenience
        collateral.relationOfMortgagor = vehicle.relationOfMortgagor
        collateral.legalValidity = vehicle.legalValidity
        collateral.firstEvaluatePrice = vehicle.firstEvaluatePrice
        collateral.firstEvaluateAccount = vehicle.firstEvaluateAccount
        collateral.latestEvaluatePrice = vehicle.latestEvaluatePrice
        collateral.latestEvaluateAccount = vehicle.latestEvaluateAccount
        collateral.latestEvaluateDate = vehicle.latestEvaluateDate
        collateral.nextEvaluateDate = vehicle.nextEvaluateDate
        collateral.actualMortgageRate = vehicle.actualMortgageRate
        collateral.mortgageRateUpperLimit = vehicle.mortgageRateUpperLimit
        collateral.description = vehicle.description
        collateral.registerFullName = vehicle.registerFullName
        collateral.registerAccount = vehicle.registerAccount
        collateral.registerDate = vehicle.registerDate
        collateral.registerUpdateDate = vehicle.registerUpdateDate
        collateral.vehicle = vehicle
        collateral.sourceClass = "vehicle"
        collateral.type = CollateralType.findByCode("vehicle")
        collateral.status = "Completed"
        collateral.stage = CollateralStage.findByCode("21")
        if (collateral.validate())
        {
            collateral.save flush: true
        }
        else
        {
            println collateral.errors
        }

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        mortgageList.each {
            def mortgageCollateral = new MortgageCollateral()
            mortgageCollateral.collateral = collateral
            mortgageCollateral.mortgage = Mortgage.findById(it)
            if (mortgageCollateral.validate())
            {
                mortgageCollateral.save flush: true
            }
            else
            {
                println mortgageCollateral.errors
            }
        }

        redirect action: 'show', params: [id: collateral?.id]
    }

    def edit(Vehicle vehicle)
    {
        respond vehicle
    }

    @Transactional
    def update(Vehicle vehicle)
    {
        if (vehicle == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (vehicle.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond vehicle.errors, view: 'edit'
            return
        }

        vehicle.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'vehicle.label', default: 'Vehicle'), vehicle.id])
                redirect vehicle
            }
            '*' { respond vehicle, [status: OK] }
        }
    }

    @Transactional
    def delete(Vehicle vehicle)
    {

        if (vehicle == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        vehicle.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'vehicle.label', default: 'Vehicle'), vehicle.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'vehicle.label', default: 'Vehicle'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
